using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Caliburn.Micro;
using MediaOwl.Common;
using MediaOwl.Common.Messages;
using MediaOwl.Common.ScreenManagement;
using MediaOwl.Common.ViewModels;

namespace MediaOwl.ViewModels
{
    [Export]
    public class MainViewModel : ExtendedConductor<IWorkspace>, IHandle<ErrorMessage>
    {
        #region Properties with Backing-Fields

        [ImportMany(AllowRecomposition = true)]
        public IEnumerable<IWorkspace> Workspaces { get; set; }

        #endregion

        #region Constructor
        [ImportingConstructor]
        public MainViewModel(IEventAggregator eventAggregator)
        {
            eventAggregator.Subscribe(this);
        }
        #endregion

        #region Methods

        private void ReloadItems()
        {
            Items.Clear();
            Items.AddRange(Workspaces.OrderBy(x => x.Order));
        }

        protected override void OnActivate()
        {
            base.OnActivate();
            ReloadItems();
            if (Items.Count > 0)
            {
                ActivateItem(Items.First());
            }
        }

        public IEnumerable<IResult> ShowInfo()
        {
            yield return Show.Dialog<InfoDialogViewModel>();
        }

        public IEnumerable<IResult> SelectModules()
        {
            yield return Show.Child<ModuleViewModel>()
                .In(Parent);

            TryClose();
            Items.Clear();
        }

        #endregion

        #region IHandle<ErrorMessage>
        public void Handle(ErrorMessage message)
        {
            Run.Coroutine(ShowErrorMessage(message.Error));
        }

        private IEnumerable<IResult> ShowErrorMessage(Exception error)
        {
            yield return Show.Dialog<DialogMessageViewModel>()
                .In(this)
                .Configured(x => x.WithData(string.Format("{0}\n\n {1}", error.Message, error.StackTrace), "Error"));
        }
        #endregion
    }
}